package com.lovo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.bean.UserInfoBean;
import com.lovo.result.GlobalHandleException;
import com.lovo.result.ResponseResult;
import com.lovo.result.ResultCode;
import com.lovo.result.UserValid;
import com.lovo.service.IUserInfoService;
//import com.lovo.util.JWTUtil;
import com.lovo.util.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bdk
 * @since 2021-03-10
 */
@RestController
@ResponseResult
@RequestMapping("/users")
@Api("用户注册和登录以及查看用户信息的控制器")
public class UserInfoController {
    @Resource
    private IUserInfoService userInfoService;

    @PostMapping("/register")
    @ApiOperation(value = "注册请求")
    public Object register(@RequestBody UserInfoBean userInfoBean){
        userInfoBean.setUserPwd(DigestUtils.sha256Hex(userInfoBean.getUserPwd()));
        userInfoService.save(userInfoBean);
        return "ok";
    }

    @ApiOperation("登录方法")
    @PostMapping("/login")
    public Object login(String userName, String userPwd) throws GlobalHandleException {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_name",userName);
        wrapper.eq("user_pwd",DigestUtils.sha256Hex(userPwd));
        UserInfoBean userInfoBean = userInfoService.getOne(wrapper);
        if(userInfoBean == null){
            throw new GlobalHandleException(ResultCode.USER_LOGIN_ERROR);
        }
        String token = JWTUtil.createToken(userInfoBean.getUserName(),userInfoBean.getUserPwd(), Calendar.MINUTE,30);
        String refreshToken = JWTUtil.createToken(userInfoBean.getUserName(),userInfoBean.getUserPwd(), Calendar.DATE,7);
        Map map = new HashMap();
        map.put("token",token);
        map.put("refreshToken",refreshToken);
        return map;
    }

    /**
     * 从token中获取用户对象
     * @return
     */
    @GetMapping("/token")
    @UserValid
    public Object getUserWithToken(HttpServletRequest request){
        return SecurityUtils.getSubject().getPrincipal();
    }

}

